package com.bestcem.xm.ticket.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.ticket.controller.convert.TicketConfigVOConvert;
import com.bestcem.xm.ticket.controller.param.ticket.config.CreateConfigParam;
import com.bestcem.xm.ticket.controller.param.ticket.config.TicketRuleParam;
import com.bestcem.xm.ticket.controller.param.ticket.config.createParam.ConditionParam;
import com.bestcem.xm.ticket.controller.vo.ticket.config.TicketConfigInfoVO;
import com.bestcem.xm.ticket.controller.vo.ticket.config.TicketConfigRuleVO;
import com.bestcem.xm.ticket.dao.TicketRuleDao;
import com.bestcem.xm.ticket.entity.mongo.TicketRule;
import com.bestcem.xm.ticket.enums.TicketRuleTypeEnum;
import com.bestcem.xm.ticket.service.TicketRuleService;
import com.bestcem.xm.ticket.service.convert.TicketRuleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 工单规则Service
 *
 * @author jy.zhao
 * @version 1.0
 * @date 2021/8/17 20:02
 **/
@Service
@Slf4j
public class TicketRuleServiceImpl implements TicketRuleService {

    @Autowired
    private TicketRuleDao ticketRuleDao;

    @Resource
    private TicketRuleMapper ticketRuleMapper;

    @Override
    public TicketRule.Condition getTicketRuleCondition(String id) {
        TicketRule ticketRule = ticketRuleDao.findById(id);
        if (Validator.isNull(ticketRule) || Validator.isNull(ticketRule.getCondition())) {
            return null;
        }
        TicketRule.Condition condition = ticketRule.getCondition();
        condition.setRuleType(ticketRule.getType());
        return condition;
    }

    @Override
    public TicketConfigInfoVO parseRuleJsonData(TicketConfigInfoVO ticketConfigInfoVO) {
        if (ObjectId.isValid(ticketConfigInfoVO.getTicketRuleId())) {
            // 查询行动触发条件信息
            TicketRule ticketRule = ticketRuleDao.findById(ticketConfigInfoVO.getTicketRuleId());
            if (Objects.nonNull(ticketRule)) {
                ticketConfigInfoVO.setType(ticketRule.getType());
                ticketConfigInfoVO.setCondition(TicketConfigRuleVO.Condition.getInstance(ticketRule.getCondition()));
            } else {
                ticketConfigInfoVO.setType(TicketRuleTypeEnum.SIMPLE.getIndex());
            }
        }

        ticketConfigInfoVO.setStatusRuleList(new ArrayList<>());
        if (!CollectionUtils.isEmpty(ticketConfigInfoVO.getStatusRuleJsonList())) {
            List<JSONObject> statusRuleJsonList = ticketConfigInfoVO.getStatusRuleJsonList();
            // 解析触发条件信息
            ArrayList<String> ruleIds = new ArrayList<>(10);
            for (JSONObject jsonObject : statusRuleJsonList) {
                ruleIds.addAll(jsonObject.keySet());
            }
            List<TicketRule> ticketRules = ticketRuleDao.listByIds(ruleIds, ticketConfigInfoVO.getId());
            List<TicketConfigRuleVO> statusRuleList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(ticketRules)) {
                for (TicketRule ticketRule : ticketRules) {
                    TicketConfigRuleVO ticketConfigRuleVO = TicketConfigVOConvert.entityToTicketConfigRuleVO(ticketRule);
                    if (Objects.nonNull(ticketConfigRuleVO)) {
                        statusRuleList.add(ticketConfigRuleVO);
                    }
                }
            }
            ticketConfigInfoVO.setStatusRuleList(statusRuleList);
        }

        return ticketConfigInfoVO;
    }


    @Override
    public ServiceResult<String> createTicketRule(String ticketConfigId, CreateConfigParam param) {

        TicketRule.Condition condition = ConditionParam.paramToEntity(param.getCondition());
        Integer rType = param.getRType();
        if (Objects.isNull(condition) || Objects.isNull(rType)) {
            log.error("创建工单生产规则, condition:{},rType:{}", condition, rType);
            return ServiceResult.fail("缺少必填参数");
        }
        if (!ObjectId.isValid(ticketConfigId)) {
            return ServiceResult.fail("TicketConfig未找到");
        }

        TicketRule ticketRule = new TicketRule();
        ticketRule.setTicketConfigId(ticketConfigId);
        ticketRule.setSurveyId(param.getSurveyId());
        ticketRule.setTitle("");
        ticketRule.setCreator("");
        ticketRule.setType(param.getRType());
        ticketRule.setCondition(condition);
        ticketRule = ticketRuleDao.saveTicketRule(ticketRule);
        return ServiceResult.success(ticketRule.getId());
    }

    @Override
    public List<JSONObject> initTicketStatusChangeRule(String ticketConfigId, CreateConfigParam param) {
        List<TicketRuleParam> statusRuleList = param.getStatusRuleList();
        if (CollectionUtils.isEmpty(statusRuleList)) {
            return new ArrayList<>();
        }
        ArrayList<JSONObject> ret = new ArrayList<>();
        for (TicketRuleParam statusRule : statusRuleList) {
            if (Objects.isNull(statusRule.getCondition()) || Objects.isNull(statusRule.getOperation())) {
                continue;
            }
            statusRule.setTicketConfigId(ticketConfigId);
            if (!ObjectUtils.isEmpty(statusRule.getTitle())) {
                statusRule.setTitle("");
            }
            if (!ObjectUtils.isEmpty(statusRule.getCreator())) {
                statusRule.setCreator("");
            }
            statusRule.setOrgId(param.getOrgId());
            statusRule.setUserId(param.getUserId());
            TicketRule entity = ticketRuleMapper.paramToEntity(statusRule);
            entity = ticketRuleDao.saveTicketRule(entity);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(entity.getId(), entity.getOperation());
            ret.add(jsonObject);
        }

        return ret;
    }

    @Override
    public List<String> updateRulesV2(String ticketConfigId, List<TicketRule> ticketRules) {
        ArrayList<String> ids = new ArrayList<>(10);

        if (CollectionUtil.isNotEmpty(ticketRules)) {
            for (TicketRule ticketRule : ticketRules) {
                String id = ticketRule.getId();
                if (Objects.nonNull(id)) {
                    Integer version = ObjectUtil.isEmpty(ticketRule.getVersion()) ? 0 : ticketRule.getVersion();
                    ticketRule.setVersion(version + 1);
                    String s = ticketRuleDao.updateTicketRule(id, ticketRule);
                    if (Objects.nonNull(s)) {
                        ids.add(s);
                    }

                } else {
                    // 创建
                    ticketRule.setTicketConfigId(ticketConfigId);
                    TicketRule newTicketRule = ticketRuleDao.saveTicketRule(ticketRule);
                    if (Objects.nonNull(newTicketRule)) {
                        ids.add(newTicketRule.getId());
                    }
                }
            }
        }

        return ids;
    }
}
